package com.moyu.common.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.moyu.common.core.contants.Constants;
import com.moyu.common.core.utils.ThreadLocalUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @Author 赵彦博
 * @Date 2025/3/26 0:12
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        // 创建人  获取当前用户用户id  如何获取当前调用接口的用户的id呢？
        Object userIdObj = ThreadLocalUtils.get(Constants.USER_ID, Long.class);
        Long userId = convertToLong(userIdObj);
        this.strictInsertFill(metaObject, "createBy", Long.class, userId);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        Object userIdObj = ThreadLocalUtils.get(Constants.USER_ID, Long.class);
        Long userId = convertToLong(userIdObj);
        this.strictUpdateFill(metaObject, "updateBy", Long.class, userId);
    }

    private Long convertToLong(Object obj) {
        if (obj == null) {
            return null;
        }
        if (obj instanceof Long) {
            return (Long) obj;
        }
        if (obj instanceof String) {
            try {
                return Long.parseLong((String) obj);
            } catch (NumberFormatException e) {
                // 处理转换失败的情况，可根据实际需求调整
                System.err.println("Failed to convert string to long: " + obj);
                return null;
            }
        }
        return null;
    }
}
